<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\CategoryModel;
use app\model\DistrictCodesModel;
use app\model\QuotesModel;
use app\model\RedisModel;
use app\model\UserUseDiscountCodeLogModel;
use think\App;
use think\facade\Db;

class DiscountCodes extends Base {

    protected $middleware = [Auth::class];
    private $model;

    private $categoryModel;

    public $cacheKey="discount:codes:";

    private $req;

    private $page;

    private $limit;

    private $aid;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 999999;

        $this->model = new DistrictCodesModel();

        $this->categoryModel = new CategoryModel();

        $this->aid = $this->isLogin();
    }

    /*
     * 获取店铺列表
     * */
    public function getList(){

        $where =[];
        if (!empty($this->req["code"])) {
            $where[] = ["code", "=", $this->req["code"]];
        }

        if (!empty($this->req["type"])) {
            $where[] = ["type", "=", $this->req["type"]];
        }

        if (isset($this->req["use_status"]) && $this->req["use_status"] != "" && in_array($this->req["use_status"],[-2,-1,0,1,2]) ) {
            $where[] = ["use_status", "=", $this->req["use_status"]];
        }

        $list = $this->model->getList($where,$this->page,$this->limit,["created_at"=>"DESC"]);

        $total = $this->model->getTotal($where);

        return $this->succData($total,$list);

    }


    /*
     * 添加
     * */
    public function add()
    {

        $code = generateRandomCode();

        if(empty($this->req['name'])){
            return $this->fail("名称不能为空");
        }

        if(!in_array($this->req['type'],['percentage','fixed_amount'])){
            return $this->fail("优惠码类型只能是折扣类型或则满减类型");
        }

        if($this->req['type'] == 'percentage'  &&  ($this->req['discount_val'] <= 0 || $this->req['discount_val'] >= 1)){
            return $this->fail("折扣率的值只能是在0-1之间的小数");
        }

        if($this->req['type'] == 'fixed_amount'  &&  ($this->req['min_order_amount'] < $this->req['discount_amount'])){
            return $this->fail("满减劵，减免金额必须大于满金额");
        }


        if(strtotime($this->req['start_time']) >= strtotime($this->req['end_time'])){
            return $this->fail("开始时间不能大于结束时间");
        }


        if(strtotime($this->req['end_time']) <= time()){
            return $this->fail("结束时间必须大于当前时间");
        }

        $useDesc ="";
        $allList = $this->categoryModel->getList(["category_status"=>1]);
        if(isset($this->req['category_pid']) && $this->req['category_pid'] == 0) {
            $useDesc = "全场";
            $where=[];
            $where[] = ["category_status","=",1];
            $where[] = ["category_pid","<>",0];
            $idList = array_column($this->categoryModel->getList($where),"category_id");
        }elseif(isset($this->req['category_pid']) && $this->req['category_pid'] == 1){
            $useDesc = "正食类";
            $where=[];
            $where[] = ["category_status","=",1];
            $where[] = ["category_pid","=",1];
            $idList = array_column($this->categoryModel->getList($where),"category_id");
        }elseif(isset($this->req['category_pid']) && $this->req['category_pid'] == 2){
            $where=[];
            $where[] = ["category_status","=",1];
            $where[] = ["category_pid","=",2];
            $idList = array_column($this->categoryModel->getList($where),"category_id");
            $useDesc = "正气生活类";
        }else{
            $idList = $this->req['category_ids'];
            if($this->req['category_ids'] == array_column($allList,"category_id")){
                $useDesc = "全场";
            }

            $zsList = $this->categoryModel->getList(["category_status"=>1,"category_pid"=>1]);
            if($this->req['category_ids'] == array_column($zsList,"category_id")){
                $useDesc = "正食类";
            }

            $zqList = $this->categoryModel->getList(["category_status"=>1,"category_pid"=>2]);
            if($this->req['category_ids'] == array_column($zqList,"category_id")){
                $useDesc = "正气生活类";
            }

            if(empty($useDesc) && !empty($this->req['category_ids'])){
                foreach ($allList as $one){
                    if(in_array($one["category_id"],$this->req['category_ids'])){
                        $useDesc .= $one["category_name"]."，";
                    }
                }
                $useDesc = trim($useDesc,"，");
            }
        }


        $res = $this->model->insertGetId([
            "code"=>$code,
            "name"=>trim($this->req['name']),
            "type"=>trim($this->req['type']),
            "discount_val"=>$this->req['discount_val'],
            "start_time"=>$this->req['start_time'],
            "end_time"=>$this->req['end_time'],
            "max_uses"=>isset($this->req['max_uses']) ? $this->req['max_uses'] : 0,
            "single_use_per_user"=>isset($this->req['single_use_per_user']) ? $this->req['single_use_per_user'] : 1,
            "min_order_amount"=>isset($this->req['min_order_amount']) ? $this->req['min_order_amount'] * 100 : 0,
            "discount_amount"=>isset($this->req['discount_amount']) ? $this->req['discount_amount'] * 100 : 0,
            "last_updated_by"=>$this->aid,
            "use_desc"=>$useDesc,
            "category_ids"=>!empty($idList) ? implode(",",$idList) : null,
            "category_pid"=>isset($this->req['category_pid']) ? $this->req['category_pid'] : null,
        ]);


        if($res){
            return $this->succ($this->model->getInfo($code));
        }else{
            return $this->fail();
        }
    }


    public function pause()
    {
        if(!isset($this->req['code']) || empty($this->req['code'])){
            return $this->fail("请选择要失效的优惠码");
        }

        $res = $this->model->where("code",$this->req['code'])->save(["is_delete"=>1,"use_status"=>-2]);
        if($res){
            $this->delCache($this->req['code']);
            return $this->succ();
        }else{
            return $this->fail();
        }
    }



    public function del()
    {
        if(!isset($this->req['code']) || empty($this->req['code'])){
            return $this->fail("请选择要失效的优惠码");
        }

        if((new UserUseDiscountCodeLogModel())->getTotal(["code"=>$this->req['code']]) > 0 ){
            return $this->fail("已存在使用记录，无法删除");
        }

        $res = $this->model->where("code",$this->req['code'])->delete();
        if($res){
            $this->delCache($this->req['code']);
            return $this->succ();
        }else{
            return $this->fail();
        }
    }



    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }
}
